package com.songminju.jdagger;

import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/*
@User mejee song
@Date 2017/9/12 
@Description 
*/
public class JDFile {

	public static void copyFile(String src, String desc) throws IOException {
		try (InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(desc)) {
			copyFile(in, out);
		}
	}

	public static void copyFile(File src, File desc) throws IOException {
		try (InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(desc)) {
			copyFile(in, out);
		}
	}

	/**
	 * @author song(mejeesong@qq.com)
	 * @date 2018年3月10日
	 * @param in
	 * @param out
	 * @throws IOException
	 *             此方法并不会关闭流.
	 */
	public static void copyFile(InputStream in, OutputStream out) throws IOException {
		byte[] buffer = new byte[32];
		int len = 0;
		while ((len = in.read(buffer)) > 0) {
			out.write(buffer, 0, len);
		}
	}

	public static Exception copyFileSilent(File src, File desc) {
		try {
			copyFile(src, desc);
		} catch (IOException e) {
			return e;
		}
		return null;
	}

	public static Exception copyFileSilent(String src, String desc) {
		try {
			copyFile(src, desc);
		} catch (IOException e) {
			return e;
		}
		return null;
	}

	public static Exception copyFileSilent(InputStream in, OutputStream out) {
		try {
			copyFile(in, out);
		} catch (IOException e) {
			return e;
		}
		return null;
	}

	public static void listFiles(File dir, List<File> files) {
		if (dir.isFile()) {
			files.add(dir);
			return;
		}
		for (File f : dir.listFiles()) {
			listFiles(f, files);
		}
	}

	/**
	*@author song(mejeesong@qq.com)
	*@date 2018年3月10日
	*@param distFile 生成的文件路径
	*@param files 要打包的文件集合，key为文件在zip包里对应的路径及名字,value为文件全路径，
	*@return
	*@throws IOException
	*
	*/
	public static void compressToZip(String distFile, Map<String, String> files) throws IOException {
		File dist = new File(distFile);
		File parent = dist.getParentFile();
		if (!parent.exists()) {
			parent.mkdir();
		}
		if (!dist.exists()) {
			dist.createNewFile();
		}
		try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dist));
				ZipOutputStream zos = new ZipOutputStream(bos);) {
			for (String name : files.keySet()) {
				ZipEntry entry = new ZipEntry(name);
				zos.putNextEntry(entry);
				try (BufferedInputStream bis = new BufferedInputStream(
						new FileInputStream(new File(files.get(name))))) {
					byte[] b = new byte[32];
					int len = 0;
					while ((len = bis.read(b)) != -1) {
						zos.write(b, 0, len);
					}
				}
				zos.closeEntry();
			}
		}
	}

}
